package com.laycoding.layrpc.config.server;

import com.laycoding.layrpc.common.SpringUtils;
import com.laycoding.layrpc.config.client.LayRpcServiceScan;
import com.laycoding.layrpc.entity.LayRpcProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@EnableConfigurationProperties(LayRpcProperties.class)
@Slf4j
public class LayRpcServerAutoConfig {

    @Autowired
    private LayRpcProperties layRpcProperties;

    /*@Bean
    public static ServiceBeanDefinitionRegistry serviceBeanDefinitionRegistry(){
        return new ServiceBeanDefinitionRegistry();
    }*/

    @Bean(name = "curatorFramework",destroyMethod = "close")
    public  CuratorFramework curatorFramework() {
        CuratorFramework cur = CuratorFrameworkFactory.builder()
                .connectString(layRpcProperties.getZookeeper())
                .connectionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        cur.start();
        return cur;
    }
    @Bean
    @ConditionalOnBean(name = "curatorFramework")
    public LayRpcRegistry layRpcRegistry(CuratorFramework curatorFramework){
        return new LayRpcRegistry(curatorFramework);
    }
    @Bean
    public SpringUtils springUtils(){
        return  new SpringUtils();
    }
    @Bean
    @ConditionalOnBean(name = "layRpcRegistry")
    public RpcServerCommandLine rpcServerCommandLine(){
        return new RpcServerCommandLine(layRpcProperties);
    }
}
